<template>
  <div class="wrap">
    <!-- 对话框 -->
    <div class="dialog-wrap">
      <!-- 添加ppt的dialog -->
      <v-dialog v-model="addPPTDialog" width="500" persistent>
        <v-card>
          <v-card-title class="text-h5"> 添加文档 </v-card-title>
          <v-sheet elevation="0" class="px-6 pt-2">
            <v-text-field
              label="文档名称"
              placeholder="请输入文档名称"
              outlined
              v-model="addPPTForm.title"
              dense
            ></v-text-field>
            <v-textarea
              label="文档介绍"
              placeholder="请输入文档介绍"
              outlined
              height="100"
              no-resize
              v-model="addPPTForm.intro"
              dense
            ></v-textarea>
            <v-select
              v-model="addPPTForm.tag"
              :items="realItemList"
              chips
              dense
              label="标签"
              multiple
              outlined
            ></v-select>
            <v-text-field
              label="文档封面"
              placeholder="请输入文档封面链接"
              outlined
              v-model="addPPTForm.cover"
              dense
            ></v-text-field>
          </v-sheet>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" text @click="closePPTDialog"> 取消 </v-btn>
            <v-btn color="primary" text @click="addPPT"> 确定 </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
      <!-- 删除ppt的dialog -->
      <v-dialog v-model="delPPTDialog" width="350" persistent>
        <v-card>
          <v-card-title class="text-h5"> 提示 </v-card-title>
          <v-card-text class="text-subtitle-1">是否删除该文档？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" text @click="delPPTDialog = false">
              取消
            </v-btn>
            <v-btn color="primary" text @click="delPPT"> 确定 </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
      <!-- 编辑ppt信息的dialog -->
      <v-dialog v-model="modifyPPTDialog" width="500" persistent>
        <v-card>
          <v-card-title class="text-h5"> 修改文档信息 </v-card-title>
          <v-sheet elevation="0" class="px-6 pt-2">
            <v-text-field
              label="文档名称"
              placeholder="请输入文档名称"
              outlined
              v-model="modifyPPTForm.title"
              dense
            ></v-text-field>
            <v-textarea
              label="文档介绍"
              placeholder="请输入文档介绍"
              outlined
              height="100"
              no-resize
              v-model="modifyPPTForm.intro"
              dense
            ></v-textarea>
            <v-select
              v-model="modifyPPTForm.tag"
              :items="modifyTagList"
              chips
              dense
              label="标签"
              multiple
              outlined
            ></v-select>
            <v-text-field
              label="文档封面"
              placeholder="请输入文档封面链接"
              outlined
              v-model="modifyPPTForm.cover"
              dense
            ></v-text-field>
          </v-sheet>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" text @click="modifyPPTDialog = false">
              取消
            </v-btn>
            <v-btn color="primary" text @click="modifyPPT"> 确定 </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
      <!-- 删除标签的dialog -->
      <v-dialog v-model="delTagDialog" width="350" persistent>
        <v-card>
          <v-card-title class="text-h5"> 提示 </v-card-title>
          <v-card-text class="text-subtitle-1">是否删除该标签？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" text @click="delTagDialog = false">
              取消
            </v-btn>
            <v-btn color="primary" text @click="delTag"> 确定 </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
      <!-- 添加标签的dialog -->
      <v-dialog v-model="addTagDialog" width="500" persistent>
        <v-card>
          <v-card-title class="text-h5"> 添加标签 </v-card-title>
          <v-sheet elevation="0" class="px-6 pt-2">
            <v-text-field
              label="标签名称"
              placeholder="请输入标签名称"
              outlined
              dense
              v-model="tagName"
            ></v-text-field>
          </v-sheet>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" text @click="addTagDialog = false">
              取消
            </v-btn>
            <v-btn color="primary" text @click="addTag"> 确定 </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </div>


    <!-- 标签 -->
    <v-sheet elevation="0" class="pa-4 pb-0" style="background-color: rgb(248, 248, 248);">
      <v-chip
        v-for="(item, index) in tagList"
        :key="index"
        class="ma-2"
        color="primary"
        close
        @click:close="openDelTagDialog(item.id)"
        >{{ item.name }}</v-chip
      >
      <v-chip color="primary" outlined class="ma-2" @click="openAddTagDialog"
        ><v-icon>add</v-icon></v-chip
      >
    </v-sheet>

    <v-sheet class="px-6 pt-3 pb-0" style="background-color: rgb(248, 248, 248);">
      <v-row justify="start" no-gutters>
        <v-sheet width="260" class="mr-4" style="background-color: rgb(248, 248, 248);">
          <v-text-field
            full-width
            rounded
            label="请输入标签名称"
            solo
            hide-details
            class="pb-0"
            append-icon="search"
            v-model="searchForm.tag"
            @keydown.enter="handleSearch"
            @click:append="handleSearch"
          ></v-text-field>
        </v-sheet>
        <v-sheet width="660" class="mr-4" style="background-color: rgb(248, 248, 248);">
          <v-text-field
            full-width
            rounded
            label="请输入文档标题关键词"
            solo
            hide-details
            append-icon="search"
            class="pb-0"
            v-model="searchForm.title"
            @keydown.enter="handleSearch"
            @click:append="handleSearch"
          ></v-text-field>
        </v-sheet>
        <v-sheet class="mr-4" style="background-color: rgb(248, 248, 248);">
          <v-btn
            height="56"
            color="warning"
            @click="resetSearch"
            fab
            elevation="2"
            ><v-icon>restart_alt</v-icon></v-btn
          >
        </v-sheet>
        <v-sheet class="mr-4" style="background-color: rgb(248, 248, 248);">
          <v-btn
            height="56"
            elevation="1"
            fab
            color="primary"
            @click="addPPTDialog = true"
            ><v-icon>add</v-icon></v-btn
          >
        </v-sheet>
        <v-spacer></v-spacer>
      </v-row>
    </v-sheet>

    <v-sheet class="pa-3" style="background-color: rgb(248, 248, 248);">
      <v-sheet v-if="pptList.length === 0" class="pa-4 py-10 text-h2" style="background-color: rgb(248, 248, 248);"
        >什么都没有找到哦🤪</v-sheet
      >
      <v-row justify="start" no-gutters v-else>
        <v-card
          max-width="280"
          v-for="(item, index) in pptList"
          :key="index"
          class="ma-3"
        >
          <v-img
            lazy-src="https://cc.lzsjl.top/leazerfspace.jpg"
            class="white--text align-end"
            height="157.5"
            :src="item.cover || 'https://cc.lzsjl.top/leazerfspace.jpg'"
          >
            <v-card-title>{{ item.title }}</v-card-title>
          </v-img>

          <v-card-subtitle class="pb-1">
            {{ item.intro ? item.intro : '这里什么都没有' }}
          </v-card-subtitle>

          <v-card-text class="text--primary py-0 px-3">
            <v-chip
              small
              outlined
              label
              v-for="(tag, index) in JSON.parse(item.tag)"
              :key="index"
              class="ma-1"
              color="primary"
              >{{ tag }}</v-chip
            >
          </v-card-text>

          <v-card-actions class="pt-1">
            <div class="pl-2 text-body-2" style="color: #757575">
              {{ realTime(item.update_time) }}
            </div>
            <v-spacer></v-spacer>
            <v-btn text color="primary" @click="editPPT(item.id)">编辑</v-btn>
            <v-menu offset-y>
              <template v-slot:activator="{ on, attrs }">
                <v-btn color="primary" icon v-bind="attrs" v-on="on"
                  ><v-icon>more_vert</v-icon></v-btn
                >
              </template>
              <v-list dense flat>
                <v-list-item-group>
                  <v-list-item @click="look(item.id)">预览文档</v-list-item>
                  <v-list-item @click="openShowPPT(item.id)"
                    >放映文档</v-list-item
                  >
                  <v-list-item @click="openModifyPPTDialog(item)"
                    >修改信息</v-list-item
                  >
                  <v-list-item @click="openDelPPTDialog(item.id)"
                    >删除文档</v-list-item
                  >
                </v-list-item-group>
              </v-list>
            </v-menu>
          </v-card-actions>
        </v-card>
      </v-row>
    </v-sheet>

    <v-row justify="start" class="ma-4">
      <v-pagination
        v-model="pageNum"
        class="ma-0"
        :length="pageLen"
        :total-visible="15"
        @input="changePage"
      ></v-pagination>
    </v-row>

    <v-dialog v-model="lookPanelShow" width="auto" @click:outside="closeLook">
      <v-card class="d-flex pa-4">
        <canvas
          id="showCanv"
          ref="showCanv"
          width="960"
          height="540"
          class="show-canv"
        ></canvas>
        <v-list
          class="overflow-x-hidden pa-0"
          height="544"
          style="overflow-y: scroll"
        >
          <v-list-item
            v-for="(item, index) in svgArray"
            :key="index"
            :class="index === svgArray.length - 1 ? '' : 'mb-3'"
            class="dom-hover"
            @click="changeTempCanv(index)"
          >
            <v-img
              :aspect-ratio="16 / 9"
              lazy-src="https://cc.lzsjl.top/leazerfspacewait.jpg"
              height="90"
              width="160"
              :src="item"
              :class="whichCanv === index ? 'has-border' : 'no-border'"
            ></v-img>
          </v-list-item>
        </v-list>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { getTag, delTag, addTag } from '@/api/tag'
import { getPPT, delPPT, addPPT, updatePPT, getOnePPT } from '@/api/ppt'
import { formatTime } from '@/utils/index.js'
import { fabric } from 'fabric'
export default {
  data() {
    return {
      whichCanv: 0,
      svgArray: ['https://cc.lzsjl.top/leazerfspacewait.jpg'],
      ow: 1920,
      oh: 1080,
      tempPPT: {},
      lookPanelShow: false,
      total: 0,
      pageNum: 1,
      pageSize: 10,
      otherTagList: [],
      modifyPPTForm: {
        id: 0,
        title: '',
        intro: '',
        cover: '',
        tag: []
      },
      searchForm: {
        tag: '',
        title: ''
      },
      addPPTForm: {
        title: '',
        intro: '',
        cover: '',
        tag: []
      },
      addPPTDialog: false,
      delPPTId: 0,
      delPPTDialog: false,
      modifyPPTDialog: false,
      pptList: [],
      delTagDialog: false,
      tagList: [],
      delTagId: 0,
      addTagDialog: false,
      tagName: ''
    }
  },
  computed: {
    pageLen() {
      if (this.total === 0) {
        return 1
      }
      return parseInt((this.total - 1) / this.pageSize) + 1
    },
    modifyTagList() {
      const tagList = new Set([...this.otherTagList, ...this.realItemList])
      return [...tagList]
    },
    realItemList() {
      return this.tagList.map((item) => item.name)
    },
    realTime() {
      return (time) => {
        return formatTime(time)
      }
    }
  },
  mounted() {
    this.initTempCanv()
    this.getTag()
    this.getPPT()
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 只有编辑ppt页面返回后才会重新加载数据
      if (from.name === 'ppt') {
        vm.getPPT()
      }
    })
  },
  // activated() { },
  methods: {
    closePPTDialog() {
      this.addPPTDialog = false
      this.addPPTForm.title = ''
      this.addPPTForm.intro = ''
      this.addPPTForm.cover = ''
      this.addPPTForm.tag = []
    },
    closeLook() {
      this.whichCanv = 0
      this.svgArray = ['https://cc.lzsjl.top/leazerfspacewait.jpg']
    },
    changeTempCanv(index) {
      this.whichCanv = index
      this.renderCanv()
    },
    renderCanv() {
      this.showCanv.loadFromJSON(this.tempPPT.content[this.whichCanv])
    },
    initTempCanv() {
      // 初始化临时画布
      this.tempCanv = new fabric.StaticCanvas('', {
        backgroundColor: 'white',
        width: this.ow,
        height: this.oh
      })
      this.tempCanv.setZoom(1 / 12)
      this.tempCanv.setWidth(this.ow / 12)
      this.tempCanv.setHeight(this.oh / 12)
    },
    openShowPPT(id) {
      this.$router.push({ name: 'movie', params: { id: id } })
    },
    initShowCanv() {
      // 初始化临时画布
      this.showCanv = new fabric.StaticCanvas('showCanv', {
        backgroundColor: 'blue',
        width: this.ow,
        height: this.oh
      })
      this.showCanv.setZoom(0.5)
      this.showCanv.setWidth(this.ow * 0.5)
      this.showCanv.setHeight(this.oh * 0.5)
    },
    look(id) {
      this.$layer.show()
      this.lookPanelShow = true
      getOnePPT({ id: id })
        .then((res) => {
          // 获取所有ppt的照片显示
          this.tempPPT = res.data.data
          this.tempPPT.content = JSON.parse(this.tempPPT.content)
          this.getSvgArr()
          // 初始化左侧画布并渲染
          if (!this.showCanv) {
            this.initShowCanv()
          }
          this.renderCanv()
        })
        .catch((err) => err)
    },
    async getSvgArr() {
      // 这里要用同步，因为图片加载会出现左侧预览问题
      for (let i = 0; i < this.tempPPT.content.length; i++) {
        await new Promise((resolve) => {
          this.tempCanv.loadFromJSON(this.tempPPT.content[i], () => {
            resolve()
          })
        }).then(() => {
          this.$set(this.svgArray, i, this.getSvg())
        })
      }
      this.$layer.hide()
    },
    getSvg() {
      return this.tempCanv.toDataURL({
        format: 'jpeg',
        quality: 0.4,
        multiplier: 1
      })
    },
    editPPT(id) {
      this.$router.push({ name: 'ppt', params: { id: id } })
    },
    changePage() {
      this.getPPT()
    },
    resetSearch() {
      this.searchForm.tag = ''
      this.searchForm.title = ''
      this.getPPT()
    },
    handleSearch() {
      this.pageNum = 1
      this.getPPT()
    },
    modifyPPT() {
      updatePPT({
        id: this.modifyPPTForm.id,
        title: this.modifyPPTForm.title,
        intro: this.modifyPPTForm.intro,
        cover: this.modifyPPTForm.cover,
        tag: JSON.stringify(this.modifyPPTForm.tag)
      })
        .then(() => {
          this.getPPT()
          this.$toast.success('更新文档成功')
          this.modifyPPTDialog = false
        })
        .catch(() => {})
    },
    addPPT() {
      if (!this.addPPTForm.title) {
        this.$toast.error('请输入文档标题')
        return
      }
      if (this.addPPTForm.tag.length === 0) {
        this.$toast.error('请选择文档标签')
        return
      }
      addPPT({
        title: this.addPPTForm.title,
        tag: JSON.stringify(this.addPPTForm.tag),
        cover: this.addPPTForm.cover,
        intro: this.addPPTForm.intro
      })
        .then(() => {
          this.getPPT()
          this.$toast.success('添加成功')
          this.addPPTDialog = false
          this.addPPTForm.title = ''
          this.addPPTForm.intro = ''
          this.addPPTForm.cover = ''
          this.addPPTForm.tag = []
        })
        .catch(() => {})
    },
    delPPT() {
      delPPT({ id: this.delPPTId })
        .then(() => {
          this.total--
          if (this.pageNum > this.pageLen) {
            this.pageNum = this.pageNum - 1 === 0 ? 1 : this.pageNum - 1
          }
          this.getPPT()
          this.$toast.success('删除成功')
          this.delPPTDialog = false
        })
        .catch(() => {})
    },
    openDelPPTDialog(id) {
      this.delPPTId = id
      this.delPPTDialog = true
    },
    openModifyPPTDialog(item) {
      this.modifyPPTForm.id = item.id
      this.modifyPPTForm.title = item.title
      this.modifyPPTForm.intro = item.intro
      this.modifyPPTForm.cover = item.cover
      this.otherTagList = JSON.parse(item.tag)
      this.modifyPPTForm.tag = JSON.parse(item.tag)
      this.modifyPPTDialog = true
    },
    getPPT() {
      this.$loading.show()
      getPPT({
        title: this.searchForm.title,
        tag: this.searchForm.tag,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
        .then((res) => {
          this.pptList = res.data.data.pptList
          this.total = res.data.data.total
        })
        .catch(() => {})
        .complete(() => {
          this.$loading.hide()
        })
    },
    getTag() {
      getTag()
        .then((res) => {
          this.tagList = res.data.data
        })
        .catch(() => {})
    },
    openDelTagDialog(id) {
      this.delTagId = id
      this.delTagDialog = true
    },
    delTag() {
      delTag({ id: this.delTagId })
        .then(() => {
          this.$toast.success('删除成功')
          this.getTag()
          this.delTagDialog = false
        })
        .catch(() => {})
    },
    openAddTagDialog() {
      this.addTagDialog = true
    },
    addTag() {
      addTag({ name: this.tagName })
        .then(() => {
          this.$toast.success('添加成功')
          this.getTag()
          this.tagName = ''
          this.addTagDialog = false
        })
        .catch(() => {})
    },
    //全屏
    fullScreen() {
      const el = document.documentElement
      const rfs =
        el.requestFullScreen ||
        el.webkitRequestFullScreen ||
        el.mozRequestFullScreen ||
        el.msRequestFullScreen

      if (rfs) {
        rfs.call(el)
      }
    },
    //退出全屏
    exitScreen() {
      const el = document
      const cfs =
        el.cancelFullScreen ||
        el.webkitCancelFullScreen ||
        el.mozCancelFullScreen ||
        el.exitFullScreen

      if (cfs) {
        cfs.call(el)
      }
    }
  }
}
</script>

<style scoped>
.wrap {
  min-height: 100vh;
  background: rgb(248, 248, 248);
}
.has-border {
  border: 2px solid blue;
}
.no-border {
  border: 2px solid rgb(197, 197, 197);
}
.dom-hover:hover {
  cursor: pointer;
}
.show-canv {
  border: 2px solid rgb(197, 197, 197);
  border-radius: 0;
  box-sizing: content-box;
}
</style>
